<?php
/**
 * curl请求类
 */
namespace common\helpers;

class ShowCurl
{
    public static function http_curl ($url,$data,$type='get',$format=false,$timeout=5) {
        $ch = curl_init();
        $url = rtrim($url);
        $type = strtolower($type); //转为小写
        $format = strtolower($format);
        if($data){
            if(is_array($data)){
                if($format == 'image'){
                    $query_string = $data;
                }else{
                    $query_string = http_build_query($data);
                }
            }else{
                $query_string = $data;
            }       
        }else{
            $query_string = "";
        }

         if(stripos($url,"https://")!==FALSE) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
         }       
        switch($type){
            case 'post' :
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
                break;
            case 'get' :
                if (strstr($url, '?')) {
                    $url .= '&'.$query_string;
                } else {
                    $url .= '?'.$query_string;
                }
                break;
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        if($format == 'json'){
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: text/plain',
                'Content-Length: ' . strlen($query_string))
            );      
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
